package com.lemon.common.web.interceptor;

import com.lemon.common.constant.SessionContants;
import com.lemon.common.context.SessionContext;
import com.lemon.common.util.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 拦截器
 *
 * @author ymh
 * @date 2019-04-05 14:24
 */
@Slf4j
public class MvcInterceptor implements HandlerInterceptor {

    /**
     * 请求处理之前执行
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取 cookie
        Cookie cookie = CookieUtils.getCookie(request, "JSESSIONID");

        if (cookie == null) { // 如果 JSESSIONID 为空，就重定向到首页
            log.info("拦截未登录用户请求 " + request.getRequestURI());
            response.sendRedirect("/static/index.html");
            return false;
        }

        // 通过 sessionId 获取 session
        String sessionId = cookie.getValue();
        SessionContext sessionContext = SessionContext.getInstance();
        HttpSession session = sessionContext.getSession(sessionId);
        if (session == null) {
            log.info("拦截未登录用户请求 " + request.getRequestURI());
            response.sendRedirect("/static/index.html");
            return false;
        }

        Object user = session.getAttribute(SessionContants.SESSION_USER);
        if (user == null) { // 如果没有登录，就重定向到首页
            log.info("拦截未登录用户请求 " + request.getRequestURI());
            response.sendRedirect("/static/index.html");
            return false;
        }

        return true;
    }

    /**
     * 请求处理完成后，生成视图之前执行
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在 DispatcherServlet 完全处理完请求后被调用，可用于清理资源等
     * 当有拦截器抛出异常时，会从当前拦截器往回执行所有的拦截器的 afterCompletion()
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
